import React, { useState } from 'react';
import { View, StyleSheet, ScrollView, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import AppHeader from '../components/AppHeader';
import GradientButton from '../components/GradientButton';
import InputField from '../components/InputField';
import UploadField from '../components/UploadField';
import SelectField from '../components/SelectField';
import DateField from '../components/DateField';
import TimeField from '../components/TimeField';
import { Colors } from '../constants/colors';
import { courseService } from '../services';

export default function AddCourseScreen() {
  const navigation = useNavigation();

  const [formData, setFormData] = useState({
    title: '',
    content: '',
    introduction: '',
    coverImage: '',
    price: '',
    startDate: '',
    endDate: '',
    startTime: '',
    endTime: '',
    isPublished: '1', // 默认上架
    maxStudents: '', // 默认最大学生数量
    publisherType: '0', // 默认发布者类型
    courseType: '0', // 默认单人课
  });
  const [loading, setLoading] = useState(false);

  // 课程类型选项
  const courseTypeOptions = [
    { label: '單人課', value: '0' },
    { label: '團體課', value: '1' },
  ];



  // 验证表单
  const validateForm = () => {
    if (!formData.title.trim()) {
      Alert.alert('錯誤', '請輸入課程標題');
      return false;
    }
    if (!formData.startDate) {
      Alert.alert('錯誤', '請選擇課程開始日期');
      return false;
    }
    if (!formData.endDate) {
      Alert.alert('錯誤', '請選擇課程結束日期');
      return false;
    }
    if (!formData.startTime) {
      Alert.alert('錯誤', '請選擇開始時間');
      return false;
    }
    if (!formData.endTime) {
      Alert.alert('錯誤', '請選擇結束時間');
      return false;
    }
    if (!formData.price.trim()) {
      Alert.alert('錯誤', '請輸入課程價格');
      return false;
    }
    const price = parseFloat(formData.price);
    if (isNaN(price) || price < 0) {
      Alert.alert('錯誤', '請輸入有效的價格');
      return false;
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    try {
      const courseData = {
        title: formData.title.trim(),
        content: formData.content.trim() || undefined,
        introduction: formData.introduction.trim() || undefined,
        coverImage: formData.coverImage || undefined,
        price: formData.price,
        startDate: formData.startDate,
        endDate: formData.endDate,
        startTime: formData.startTime,
        endTime: formData.endTime,
        isPublished: formData.isPublished,
        maxStudents: parseInt(formData.maxStudents),
        currentStudents: 0, // 默认为0
        publisherType: formData.publisherType,
        courseType: formData.courseType,
      };

      console.log('📝 準備發送課程數據:', courseData);

      await courseService.addCourse(courseData);

      Alert.alert('成功', '課程創建成功', [
        { text: '確定', onPress: () => navigation.goBack() }
      ]);
    } catch (error: any) {
      console.error('創建課程失敗:', error);
      Alert.alert('創建失敗', error.message || '創建課程時發生錯誤，請稍後重試');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <AppHeader title="添加課程" showBack />
      
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        <View style={styles.form}>
          <View style={{ marginHorizontal: 4, marginTop: 16 }}><InputField label="課程標題" value={formData.title} onChangeText={(text)=>setFormData({...formData,title:text})} placeholder="請輸入課程標題" variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><InputField label="課程內容" value={formData.content} onChangeText={(text)=>setFormData({...formData,content:text})} placeholder="請輸入課程內容" multiline variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><InputField label="課程介紹" value={formData.introduction} onChangeText={(text)=>setFormData({...formData,introduction:text})} placeholder="請輸入課程介紹" multiline variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}>
            <SelectField
              label="課程類型"
              value={formData.courseType}
              options={courseTypeOptions}
              onChange={(value) => setFormData({...formData, courseType: value})}
              variant="card"
            />
          </View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}>
            <UploadField
              label="課程封面"
              uri={formData.coverImage}
              onChangeUri={(u)=>setFormData({...formData, coverImage: u || ''})}
              onUploadComplete={(ossUrl) => setFormData({...formData, coverImage: ossUrl})}
              showRightTip={false}
            />
          </View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><InputField label="收費價格" value={formData.price} onChangeText={(text)=>setFormData({...formData,price:text})} keyboardType="numeric" placeholder="輸入價格" variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><DateField label="開始日期" value={formData.startDate} onChange={(v)=>setFormData({...formData,startDate:v})} variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><DateField label="結束日期" value={formData.endDate} onChange={(v)=>setFormData({...formData,endDate:v})} variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><TimeField label="開始時間" value={formData.startTime} onChange={(v)=>setFormData({...formData,startTime:v})} variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><TimeField label="結束時間" value={formData.endTime} onChange={(v)=>setFormData({...formData,endTime:v})} variant="card" /></View>

          <View style={{ marginHorizontal: 4, marginTop: 16 }}><InputField label="最大學生數量" value={formData.maxStudents} onChangeText={(text)=>setFormData({...formData,maxStudents:text})} keyboardType="numeric" placeholder=" 輸入最大學生數量" variant="card" /></View>

          <GradientButton
            title={loading ? "創建中..." : "創建課程"}
            onPress={handleSubmit}
            disabled={loading}
            style={styles.submitButton}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  content: {
    flex: 1,
  },
  form: { padding: 24 },
  cardWrap: { backgroundColor: Colors.white, borderRadius: 12, borderWidth: 1, borderColor: Colors.gray[200], padding: 14, marginHorizontal: 4, marginTop: 16 },
  row: { flexDirection: 'row', gap: 12 },
  label: { fontSize: 16, fontWeight: '600', color: Colors.gray[700], marginBottom: 8 },

  submitButton: {
    marginTop: 32,
  },
});